
package com.english.controller;

import com.english.entity.ClassHoursLog;
import com.english.entity.CourseClass;
import com.english.entity.StudentClassHours;
import com.english.entity.StudentRecharge;
import com.english.entity.User;
import com.english.mapper.CourseClassMapper;
import com.english.mapper.StudentRechargeMapper;
import com.english.mapper.UserMapper;
import com.english.service.StudentClassHoursService;
import com.english.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.english.service.WechatPayService;

/**
 * 学生班级课时管理控制器
 *
 * @author wlq
 * @since 2025-08-06
 */
@Slf4j
@RestController
@RequestMapping("/api/student-class-hours")
@CrossOrigin(origins = "*", allowCredentials = "false", maxAge = 3600)
public class StudentClassHoursController {

    @Autowired
    private StudentClassHoursService studentClassHoursService;

    @Autowired
    private CourseClassMapper courseClassMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StudentRechargeMapper studentRechargeMapper;

    @Autowired  
    private WechatPayService wechatPayService;

    /**
     * 获取学生的所有班级课时信息
     */
    @GetMapping("/student/{studentId}")
    public R<List<StudentClassHours>> getStudentClassHours(@PathVariable Long studentId) {
        try {
            List<StudentClassHours> hoursList = studentClassHoursService.getStudentClassHours(studentId);
            return R.success("获取成功", hoursList);
        } catch (Exception e) {
            log.error("获取学生班级课时失败：{}", e.getMessage(), e);
            return R.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户的班级课时信息（前端使用）
     */
    @GetMapping("/my-hours")
    public R<Map<String, Object>> getMyClassHours(@RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 从token中获取用户信息
            User currentUser = getCurrentUserFromToken(token);
            if (currentUser == null) {
                return R.unauthorized("用户未登录");
            }

            // 获取所有班级信息
            List<CourseClass> allClasses = courseClassMapper.selectActiveClasses();

            // 获取学生的班级课时信息
            List<StudentClassHours> hoursList = studentClassHoursService.getStudentClassHours(currentUser.getId());

            // 获取总剩余课时
            Integer totalRemainingHours = studentClassHoursService.getTotalRemainingHours(currentUser.getId());

            Map<String, Object> result = new HashMap<>();
            result.put("allClasses", allClasses);
            result.put("studentHours", hoursList);
            result.put("totalRemainingHours", totalRemainingHours);

            return R.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取用户班级课时失败：{}", e.getMessage(), e);
            return R.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 获取班级的所有学生课时信息
     */
    @GetMapping("/class/{classId}")
    public R<List<StudentClassHours>> getClassStudentHours(@PathVariable Long classId) {
        try {
            List<StudentClassHours> hoursList = studentClassHoursService.getClassStudentHours(classId);
            return R.success("获取成功", hoursList);
        } catch (Exception e) {
            log.error("获取班级学生课时失败：{}", e.getMessage(), e);
            return R.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 手动调整学生班级课时
     */
    @PostMapping("/adjust")
    public R<String> adjustStudentClassHours(@RequestBody Map<String, Object> params,
                                           @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 从token中获取管理员信息
            User currentUser = getCurrentUserFromToken(token);
            if (currentUser == null || currentUser.getRole() != 1) {
                return R.unauthorized("需要管理员权限");
            }

            Long studentId = Long.valueOf(params.get("studentId").toString());
            Long classId = Long.valueOf(params.get("classId").toString());
            Integer changeValue = Integer.valueOf(params.get("changeValue").toString());
            String reason = params.get("reason").toString();

            boolean success = studentClassHoursService.adjustStudentClassHours(
                studentId, classId, changeValue,
                ClassHoursLog.ChangeType.MANUAL_ADJUSTMENT,
                "管理员手动调整",
                reason,
                currentUser.getId()
            );

            if (success) {
                return R.success("调整成功");
            } else {
                return R.error("调整失败");
            }
        } catch (Exception e) {
            log.error("调整学生班级课时失败：{}", e.getMessage(), e);
            return R.error("调整失败：" + e.getMessage());
        }
    }

    /**
     * 获取课时变动日志
     */
    @GetMapping("/logs/{studentId}")
    public R<List<ClassHoursLog>> getHoursChangeLogs(@PathVariable Long studentId,
                                                     @RequestParam(required = false) Long classId) {
        try {
            List<ClassHoursLog> logs = studentClassHoursService.getHoursChangeLog(studentId, classId);
            return R.success("获取成功", logs);
        } catch (Exception e) {
            log.error("获取课时变动日志失败：{}", e.getMessage(), e);
            return R.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 初始化学生班级课时记录
     */
    @PostMapping("/init")
    public R<String> initStudentClassHours(@RequestBody Map<String, Object> params,
                                         @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 从token中获取管理员信息
            User currentUser = getCurrentUserFromToken(token);
            if (currentUser == null || currentUser.getRole() != 1) {
                return R.unauthorized("需要管理员权限");
            }

            Long studentId = Long.valueOf(params.get("studentId").toString());
            Long classId = Long.valueOf(params.get("classId").toString());

            boolean success = studentClassHoursService.initStudentClassHours(studentId, classId);

            if (success) {
                return R.success("初始化成功");
            } else {
                return R.error("初始化失败");
            }
        } catch (Exception e) {
            log.error("初始化学生班级课时失败：{}", e.getMessage(), e);
            return R.error("初始化失败：" + e.getMessage());
        }
    }

    /**
     * 获取所有班级信息
     */
    @GetMapping("/classes")
    public R<List<CourseClass>> getAllClasses() {
        try {
            List<CourseClass> classes = courseClassMapper.selectActiveClasses();
            return R.success("获取成功", classes);
        } catch (Exception e) {
            log.error("获取班级信息失败：{}", e.getMessage(), e);
            return R.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 学生提交充值申请
     * @param token 学生token
     * @param amount 充值金额
     * @param notes 备注信息
     * @return 操作结果
     */
    @PostMapping("/submitRecharge")
    public R<String> submitRecharge(
            @RequestHeader("Authorization") String token,
            @RequestParam BigDecimal amount,
            @RequestParam(required = false) String notes) {
        try {
            Long userId = getUserId(token);

            StudentRecharge recharge = new StudentRecharge();
            recharge.setUserId(userId);
            recharge.setAmount(amount);
            recharge.setNotes(notes);
            recharge.setIsProcessed(0); // 未处理
            recharge.setRechargeTime(new Date());
            recharge.setUpdateTime(new Date());

            studentRechargeMapper.insert(recharge);

            return R.success("充值申请提交成功，请等待管理员处理", null);
        } catch (RuntimeException e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 学生查看自己的充值记录
     * @param token 学生token
     * @return 充值记录列表
     */
    @GetMapping("/myRechargeRecords")
    public R<List<StudentRecharge>> getMyRechargeRecords(@RequestHeader("Authorization") String token) {
        try {
            Long userId = getUserId(token);

            // 查询所有充值记录，按时间倒序（让前端控制显示逻辑）
            LambdaQueryWrapper<StudentRecharge> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StudentRecharge::getUserId, userId)
                       .orderByDesc(StudentRecharge::getRechargeTime);

            List<StudentRecharge> records = studentRechargeMapper.selectList(queryWrapper);

            return R.success("获取成功", records);
        } catch (RuntimeException e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 管理员同步支付状态（用于回调失败的情况）
     * @param token 管理员token
     * @return 同步结果
     */
    @PostMapping("/admin/syncPaymentStatus")
    public R<Map<String, Object>> syncPaymentStatus(@RequestHeader("Authorization") String token) {
        try {
            // 验证管理员权限
            User currentUser = getCurrentUserFromToken(token);
            if (currentUser == null || currentUser.getRole() != 1) {
                return R.unauthorized("需要管理员权限");
            }

            // 查询所有待支付状态的充值记录（可能是回调失败的）
            LambdaQueryWrapper<StudentRecharge> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StudentRecharge::getPaymentStatus, 0)
                       .isNotNull(StudentRecharge::getOrderNo)
                       .orderByDesc(StudentRecharge::getRechargeTime);

            List<StudentRecharge> pendingOrders = studentRechargeMapper.selectList(queryWrapper);
            
            int syncedCount = 0;
            int failedCount = 0;
            
            for (StudentRecharge order : pendingOrders) {
                try {
                    // 查询微信支付状态
                    Map<String, Object> orderInfo = wechatPayService.queryOrder(order.getOrderNo());
                    String tradeState = (String) orderInfo.get("trade_state");
                    
                    if ("SUCCESS".equals(tradeState)) {
                        // 支付成功，更新状态
                        order.setPaymentStatus(1);
                        order.setWechatOrderNo((String) orderInfo.get("transaction_id"));
                        order.setUpdateTime(new Date());
                        studentRechargeMapper.updateById(order);
                        syncedCount++;
                        log.info("同步支付状态成功，订单号: {}", order.getOrderNo());
                    } else if ("CLOSED".equals(tradeState) || "REVOKED".equals(tradeState)) {
                        // 订单关闭或被撤销，标记为失败
                        order.setPaymentStatus(2);
                        order.setUpdateTime(new Date());
                        studentRechargeMapper.updateById(order);
                        syncedCount++;
                    }
                } catch (Exception e) {
                    log.error("同步订单状态失败，订单号: {}, 错误: {}", order.getOrderNo(), e.getMessage());
                    failedCount++;
                }
                
                // 避免请求过于频繁
                Thread.sleep(200);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("totalChecked", pendingOrders.size());
            result.put("syncedCount", syncedCount);
            result.put("failedCount", failedCount);
            
            return R.success("同步完成", result);
            
        } catch (Exception e) {
            log.error("同步支付状态失败: {}", e.getMessage(), e);
            return R.error("同步失败：" + e.getMessage());
        }
    }

    /**
     * 从token中获取当前用户
     */
    private User getCurrentUserFromToken(String token) {
        if (token == null) {
            return null;
        }

        String wechatId = extractWechatIdFromToken(token);
        if (wechatId == null) {
            return null;
        }

        return userMapper.selectByWechatId(wechatId);
    }

    /**
     * 从token中提取wechatId
     */
    private String extractWechatIdFromToken(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        if (token != null && token.startsWith("token_")) {
            String[] parts = token.split("_");
            if (parts.length >= 2) {
                return parts[1];
            }
        }

        return null;
    }

    /**
     * 从token中获取用户ID
     */
    private Long getUserId(String token) {
        User currentUser = getCurrentUserFromToken(token);
        if (currentUser == null) {
            throw new RuntimeException("用户未登录或token无效");
        }
        return currentUser.getId();
    }

//    @PutMapping("/admin/Recharge")
//    public R<String> rechargeStudentClassHours(Long userId, Integer hours) {
//
//    }
}
